<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="checkbox" name="goods" id="phone" value="9999" />
    <label for="phone">HuaWei Meta 50 保时捷 ￥9999</label>
    <br />
    <input type="checkbox" name="goods" id="iPhone" value="5299" />
    <label for="iPhone">iPhone 14 ￥5299</label>
    <br />
    <input type="checkbox" name="goods" id="rtx" value="30000" />
    <label for="rtx">RTX 4090 ￥30000</label>
    <br />
    <input type="checkbox" name="goods" id="lv" value="49999" />
    <label for="lv">LV 包 ￥49999</label>
    <hr />
    <input type="checkbox" id="all" onclick="checkAll(this)" />
    <label for="all">全选/取消全选</label>

    <!-- <button type="button" onclick="checkAll(this)">全选</button> -->
    <button type="button" onclick="reCheck()">反选</button>

    <button type="button" onclick="clearCar()">清空购物车</button>
    总计：<span id="money">0</span> 元

    <script type="text/javascript">
      let goods = document.querySelectorAll("[name=goods]");

      let allBtn = document.querySelector("#all");

      for (let good of goods) {
        good.onclick = function (e) {
          if (good.checked) {
            checkChecked();
          } else {
            allBtn.checked = false; // 取消全选
          }
        };
      }

      function checkChecked() {
        // 检测其他商品是否都被勾选了
        for (let g of goods) {
          if (!g.checked) {
            // 有一个商品没被勾选
            allBtn.checked = false; // 取消全选
            return;
          }
        }
        allBtn.checked = true; // 全选
      }

      function checkAll(e) {
        console.log("全选/全不选");
        for (good of goods) {
          good.checked = e.checked;
        }

        // goods.forEach((e) => {
        //   e.checked = true;
        // });
      }

      function reCheck() {
        console.log("反选");
        for (let good of goods) {
          good.checked = !good.checked;
        }
        checkChecked();
      }

      function clearCar() {
        let money = 0;
        for (let good of goods) {
          if (good.checked) {
            money += parseFloat(good.value);
          }
        }
        document.querySelector("#money").innerText = money;
      }
    </script>
  </body>
</html>
